package com.xinghou.platform.dao.wzk.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.xinghou.platform.dao.bases.JdbcTemplate;
import com.xinghou.platform.dao.bases.database.CustomerContextHolder;
import com.xinghou.platform.dao.wzk.ShowcardDAO;
import com.xinghou.platform.model.wzk.Showcard;

@Repository
public class ShowcardDAOImpl implements ShowcardDAO {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public Showcard getShowcardById(String id) throws DataAccessException {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);
		String sql = "SELECT * FROM wzk.showcard  where id = ?";
		Showcard showcard = jdbcTemplate.queryForObject(sql, new Object[] { id }, new ShowcardMapper());
		CustomerContextHolder.clearCustomerType();
		return showcard;
	}
	
	public Showcard getShowcardByIdMax(int sex) throws DataAccessException {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);
		String sql = "SELECT * FROM wzk.showcard WHERE id= (SELECT MAX(a.id) FROM wzk.showcard a WHERE a.state = 0 AND a.cityID = ?)";
		Showcard showcard = jdbcTemplate.queryForObject(sql, new Object[] { sex },new ShowcardMapper());
		CustomerContextHolder.clearCustomerType();
		return showcard;
	}

	@Override
	public void updateShowcard(Showcard showcard) throws DataAccessException {
		StringBuffer strSQL = new StringBuffer("UPDATE wzk.showcard SET state = ? where id=? ");
		Object[] params = {showcard.getState(),showcard.getId()};
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_WRITE);
		int ret = jdbcTemplate.update(strSQL.toString(),params);
		CustomerContextHolder.clearCustomerType();
	}
	
	private static final class ShowcardMapper implements RowMapper<Showcard> {
		public Showcard mapRow(ResultSet rs, int rowNum) throws SQLException {
			Showcard showcard = new Showcard();
			showcard.setCityId(rs.getString("cityId"));
			showcard.setContent(rs.getString("content"));
			showcard.setId(rs.getInt("id"));
			showcard.setSex(rs.getInt("sex"));
			showcard.setState(rs.getInt("state"));
			showcard.setStore_id(rs.getInt("store_id"));
			showcard.setStore_type(rs.getInt("store_type"));
			showcard.setType(rs.getInt("type"));
			showcard.setUsearea(rs.getString("usearea"));
			showcard.setShouxu(rs.getDouble("shouxu"));
			showcard.setTranobj(rs.getInt("tranobj"));
			showcard.setTrantype(rs.getInt("trantype"));
			showcard.setTrantime(rs.getString("trantime"));
			showcard.setDiscount(rs.getString("discount"));
			showcard.setMoney(rs.getDouble("money"));
			showcard.setMinmoney(rs.getDouble("minmoney"));
			showcard.setStorename(rs.getString("storename"));
			return showcard;
		}
	}
}
